﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Text;
using Microsoft.VisualStudio.VCProjectEngine;
using EnvDTE;
using EnvDTE80;
using System.Windows.Forms;
using System.IO;
using iDocument;

namespace iMainAddin
{
	namespace iItem
    {
        public class iVcProjectEngine : iVcEngine
        {
            ~iVcProjectEngine()
            {
            }
            protected override bool Init()
            {
                return true;
            }
			public bool CreateModuleProject(DTE2 Application, String sProjectName)
            {
                Solution CurrentSolution = (Solution)Application.Solution;
                try
                {
					String sSolutionPath = Path.GetDirectoryName(CurrentSolution.FullName);
					String sProjectPath = sSolutionPath + @"\" + sProjectName;
					Directory.CreateDirectory(sProjectPath);
					sProjectPath += @"\";
					sSolutionPath += @"\";

					Project newProject = CurrentSolution.AddFromFile(@"D:\work\HelpGine9_0\bin\ModlueProject_9\ModlueProject.vcproj", false);
					m_vcProjcet = newProject.Object as VCProject;

					m_vcProjcet.RootNamespace = sProjectName;
					m_vcProjcet.Name = sProjectName;
					newProject.SaveAs(sProjectPath + sProjectName + ".vcproj");
                    CurrentSolution.SaveAs(CurrentSolution.FullName);

					IEnumerator rator = newProject.ProjectItems.GetEnumerator();
					ProjectItemCopy(rator);

					IVCCollection collection = m_vcProjcet.Configurations as IVCCollection;
					rator = collection.GetEnumerator();
					ProjectPrpertyCopy(sSolutionPath, rator);

					newProject.Save(sProjectPath + sProjectName + ".vcproj");
					CurrentSolution.SaveAs(CurrentSolution.FullName);
                }
                catch (SystemException e)
                {
                    MessageBox.Show("ERROR: " + e.Message);
                    return false;
                }
                return true;
                #region 주석

                //Solution CurrentSolution = ProjectInfo.rDte.Solution;
                //CurrentSolution.Create(@"c:\temp", "MyNewSolution");
                //CurrentSolution.SaveAs(@"c:\temp\mya.sln");
                //CurrentSolution.AddFromFile(@"C:\Program Files\Microsoft Visual Studio 8\VC\VCWizards\default.vcproj", false);
                //CurrentSolution.AddFromFile(@".\Project1.vcproj", false);
                //NewProject = (VCProject)CurrentSolution.AddFromFile(@".\ModlueProject\ModlueProject.vcproj", false);


                //    //VCToolFile vctool = m_Engine.CreateToolFile("ssss");
                //    //aProject.AddToolFile(vctool);			
                //    //VCFile file = (VCFile)aProject.AddFile("c.cpp");
                //    //VCProjectEngineEvents fdasf = (VCProjectEngineEvents)m_Engine.Events;
                //    //IVCCollection filesCollection = (IVCCollection)aProject.Files;
                //    //aProject.Save();
                //    ProjectItem aa =null;
                //    try{
                //        aa = (ProjectItem)ProjectInfo.rDte.Solution.FindProjectItem("ss.GIF");
                //    }
                //    catch (Exception e)
                //    {
                //        MessageBox.Show(e.Message);
                //    }

                //    //aa.Name = "aa.gif";
                //    //aa.Save(aa.Name);
                //    //aa.ContainingProject.Save(aa.ContainingProject.UniqueName);
                //    //Property prs;
                //    //Property prs2;
                //    //Project Proj = null;
                //    //foreach ( Project TempProj in ProjectInfo.rDte.Solution.Projects)
                //    //{
                //    //    if( TempProj.UniqueName == aa.ContainingProject.UniqueName;
                //    //}
                //    //prs = aa.Properties.Item("name");

                //    //aa.Name = "SS.GIF";
                //    //aa.Remove();

                //try{
                //        ProjectItem newaa = aa.ContainingProject.ProjectItems.AddFromFile((string)"ccS.cpp");
                //    }
                //    catch (Exception e)
                //    {
                //        MessageBox.Show(e.Message);
                //    }
                //    WindowConfigurations colWinConfig;
                //    WindowConfiguration objWinConfig;
                //    Window win;

                //    colWinConfig = ProjectInfo.rDte.WindowConfigurations;
                //    Windows m = ProjectInfo.rDte.Windows;
                //    System.Collections.IEnumerator sd = colWinConfig.GetEnumerator();
                //    sd.MoveNext();
                //    for (int i = 1; i < m.Count; i++)
                //    {
                //        win = m.Item(i);
                //                        //objWinConfig.Update();
                //    }

                //    MessageBox.Show("Number of configurations: " +
                //        colWinConfig.Count);

                //    // List all saved named window configurations.
                //    FillMsg(colWinConfig);
                //    //Create a new window configuration.
                //    objWinConfig = colWinConfig.Add("NewLayout");
                //    FillMsg(colWinConfig);
                //    // Get rid of the new window configuration.
                //    objWinConfig.Delete();
                //    MessageBox.Show("Number of configurations: " + colWinConfig.Count);
                //    FillMsg(colWinConfig);


                //    System.Collections.IEnumerator bb = aa.Properties.GetEnumerator();
                //    bool ssfa = bb.MoveNext();
                //    for (int i = 1; i < 17; i++)
                //    {
                //        //prs = aa.Properties.Item(i);
                //        //prs2 = newaa.Properties.Item(i);
                //        //object obj = prs.Object;
                //        //((Project)obj).sa
                //        //prs.Value = "dd";
                //        //prs.Value;
                //    }
                //    ////string sfsdfaas = (string)bb.Current;
                //    //Property ss = aa.Properties.Item(10);
                //    //try
                //    //{
                //    //    ss.let_Value("gc.gif");
                //    //}
                //    //catch (Exception e)
                //    //{
                //    //    MessageBox.Show(e.Message);
                //    //}
                //    //aa.Name = "gc.gif";
                //    //aa.Properties.
                //    //aa.Save("gc.c");
                //    //LoadProject();
                //    return true;
                #endregion
            }

            public bool CreateSampleProject(string sProjectName)
            {
                return true;
            }

			protected void ProjectPrpertyCopy(String solutionPath, IEnumerator configurationRator)
			{
				//IVCCollection collection = m_vcProjcet.Configurations as IVCCollection;
				//VCConfiguration property = collection.Item(1) as VCConfiguration;
				//VCPropertySheet seet = (VCPropertySheet)((IVCCollection)property.PropertySheets).Item(1);
				//IVCCollection configurations = m_vcProjcet.Configurations as IVCCollection;
				//IEnumerator configurationRator = configurations.GetEnumerator();
				while(configurationRator.MoveNext())
				{
					VCConfiguration property = configurationRator.Current as VCConfiguration;
					if (property == null)
						continue;

					String InheritedPropertySheets = null;
					IVCCollection prpertyCollection = property.PropertySheets as IVCCollection;
					IEnumerator seetRator = prpertyCollection.GetEnumerator();
					while (seetRator.MoveNext())
					{
						VCPropertySheet seet = seetRator.Current as VCPropertySheet;
						if (seet == null)
							continue;
						seet.PropertySheetFile = solutionPath + @"Property Seet\" + seet.Name + @".vsprops";
						InheritedPropertySheets += seet.PropertySheetFile;
						seet.Save();
					}
					property.InheritedPropertySheets = InheritedPropertySheets;
				}
			}

            protected void ProjectItemCopy(IEnumerator rator)
            {
				ExchangeDocument changeFile = new ExchangeDocument();
				changeFile.AddDictionary("$(ProjectName)", m_vcProjcet.Name);
				changeFile.AddDictionary("$(ProjectNameUP)", m_vcProjcet.Name.ToUpper());
				
				ProjectItem item;
				while (rator.MoveNext())
				{
				    item = rator.Current as ProjectItem;

				    if (item.Kind == "{6BB5F8EE-4483-11D3-8BCF-00C04F8EC28C}") // 물리적 파일
				    {
						String sNewFilePath = m_vcProjcet.ProjectDirectory + m_vcProjcet.Name + item.Name;
				        String sBaseFilePath = item.get_FileNames(1);
				        String baseName = iSystem.iFileAssist.RemoveExtension(item.Name);
						String sNewName = iSystem.iFileAssist.RemoveExtension(m_vcProjcet.Name + item.Name);				        

				        File.Copy(sBaseFilePath, sNewFilePath);

						// 파일 위치 변경
						Property Exe = (Property)item.Properties.Item("Extension");
				        Property property = (Property)item.Properties.Item("RelativePath"); // 11
				        property.Value = sNewFilePath;
						item.Name = sNewName + (string)Exe.Value;

						// 문서 변경(지정어 변경)
						item.Open(Constants.vsViewKindCode);
						TextDocument document = item.Document.Object("TextDocument") as TextDocument;
						if (document != null)
						{
							changeFile.Exchange(document.StartPoint, document.EndPoint);
						}
				    }
					else  // (item.Kind == "{6BB5F8F0-4483-11D3-8BCF-00C04F8EC28C}") // 프로젝트 파일
					{
						ProjectItemCopy(item.ProjectItems.GetEnumerator());
						continue;
					}
				}
            }
        }
    }
}